//
//  WJPublishVideoVC.m
//  WJBSApp
//
//  Created by dllo on 16/8/1.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJPublishVideoVC.h"
#import "WJTextView.h"
#import "WJDataManager.h"
#import "SVProgressHUD.h"
#import "WJPublishModel.h"
#import "UIImage+WJResize.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface WJPublishVideoVC ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) WJBaseView *touView;

@property (nonatomic,retain) WJTextView *textView;

@property (nonatomic,strong) WJBaseButton *rightbutton;

@property (nonatomic,strong) WJBaseButton *chooseButton;

@property (nonatomic,copy) NSString *oldPath;

@property (nonatomic,copy) NSString *neWPath;

@property (nonatomic, strong) UIImageView *picView;

@end

@implementation WJPublishVideoVC


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.textView becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createView];
    
    [self createTextView];
}

- (void)createView
{
    self.touView = [[WJBaseView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    [self.view addSubview:self.touView];
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 24, WIDTH - 200, 40)];
    lable.text = @"发表视频";
    lable.textAlignment = 1 ;
    [self.touView addSubview:lable];
    
    WJBaseButton *button = [WJBaseButton buttonWithTitle:nil frame:CGRectMake(20, 30, 50, 30) target:self action:@selector(puLeftAction)];
    button.backgroundColor = BSClearColor;
    [button setImage:[UIImage imageNamed:@"navigationButtonReturn.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"navigationButtonReturnClick.png"] forState:UIControlStateHighlighted];
    [self.touView addSubview:button];
    
    self.rightbutton = [WJBaseButton buttonWithTitle:@"发表" frame:CGRectMake(WIDTH - 70, 30, 50, 30) target:self action:@selector(puRightAction)];
    [ self.rightbutton setTitleColor:BSBlackColor forState:0];
    self.rightbutton.backgroundColor = BSClearColor;
    [self.touView addSubview: self.rightbutton];
    [self.touView layoutIfNeeded];
    
}

- (void)createTextView
{
    self.textView = [[WJTextView alloc]initWithFrame:CGRectMake(15, 64, WIDTH - 30, HEIGHT * 2 / 7)];
    [self.view addSubview:self.textView];
    _textView.alwaysBounceVertical = YES;
    _textView.delegate = self;
    _textView.placeholder = @"这里添加文字,请勿发布色情、政治等违反国家法律的内容,违者封号处理";
    self.editing = YES;
    self.textView.userInteractionEnabled = YES;
    
    self.picView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 64 + HEIGHT * 2 / 7, 100, 100)];
    self.picView.backgroundColor = BSGrayColor;
    [self.view addSubview:self.picView];
    
    self.chooseButton = [WJBaseButton buttonWithType:UIButtonTypeSystem];
     self.chooseButton.frame = CGRectMake(WIDTH / 2-50, 64 + HEIGHT * 2 / 7 + 30, 100, 30);
    [self.chooseButton setTitle:@"选择视频" forState:UIControlStateNormal];
    [self.chooseButton addTarget:self action:@selector(buttonAct:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.chooseButton];
}

- (void)puLeftAction
{
    [self.textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 选择视频
- (void)buttonAct:(WJBaseButton *)button
{
    
//    整理一下思路  获得视频之后还要将视频过转码 保存到沙河路径
    
    
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"录像" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            // 配置类型为Movie
            NSString *requireMediaType = (__bridge NSString *)kUTTypeMovie;
            picker.mediaTypes = [[NSArray alloc]initWithObjects:requireMediaType, nil];

            picker.videoQuality = UIImagePickerControllerQualityTypeMedium; //录像质量
            picker.videoMaximumDuration = 600.0f; //录像最长时间
            
        } else {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"当前设备不支持录像功能" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:^{}];
        }
        //跳转到拍摄页面
        [self presentViewController:picker animated:YES completion:nil];

        
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从本地选取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        //跳向自己的相册  让他们自己选取
        
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.allowsEditing =YES;
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:^{}];
        

        
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
    [alert addAction:action];
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:^{}];
    
}

//拍摄完成后要执行的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(__bridge NSString *)kUTTypeMovie]) {
        
        // 视频地址  这个视频是在tmp 文件夹当中
        NSURL *movieURL = [info objectForKey:UIImagePickerControllerMediaURL];
        self.oldPath = [movieURL path];
        
        self.picView.image = [UIImage imageWithVideo:movieURL];
        
        //  保存视频到相册
        UISaveVideoAtPathToSavedPhotosAlbum(_oldPath, self, nil, nil);
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

// 点击录制视频的取消执行的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}



//  点击发表进入本地
- (void)puRightAction
{
    [self.textView resignFirstResponder];
    NSLog(@"点击了发表");
    
    if (self.oldPath) {
        
        
        /** 因为我们要用text来删除文件所以必须要有文字*/
        if (self.textView.text) {
        
        NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
        NSDate*detaildate=[NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
        NSString*currentDateStr = [dateFormatter stringFromDate:detaildate];
        
        
        // 如果发表将录像写入本地
        // 创建路径
        self.neWPath = [VIDEO stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mov",currentDateStr]];
        
        // 另一个想法 将 文件拷贝到沙河里面
        BOOL result = [[NSFileManager defaultManager] copyItemAtPath:_oldPath toPath:_neWPath error:nil];
        
        if (result) {
            NSLog(@"拷贝到本地成功了");
        }
        
        
        WJPublishModel *model = [[WJPublishModel alloc]init];
        model.type = @"video";
        model.text = self.textView.text;
        model.nowTime = currentDateStr;
        UIImage *image = [UIImage imageWithVideo:[NSURL fileURLWithPath:self.neWPath]];
        model.picData = UIImageJPEGRepresentation(image, 1);
        model.videoPath = self.neWPath;
        [[WJDataManager shareFMDB]insertModel:model];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发表成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{}];
            
        }else{
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请填写描述文字" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:^{}];
            
        }
        
    }else{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"没有视频" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {}];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{}];
        
    }
}

#pragma mark -- UITextFieldDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //拖拽时 结束编辑 退出键盘
    [self.textView endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        self.textView.frame = CGRectMake(15, 64, WIDTH - 30, HEIGHT - 64 - 150);
        self.chooseButton.frame = CGRectMake(WIDTH / 2-50, HEIGHT - 100, 100, 30);
        self.picView.frame = CGRectMake(10, HEIGHT - 130, 100, 100);
    }];
}

- (void)textViewDidChange:(UITextView *)textView{
    //判读是否有文字  设置发表按钮的状态
    self.rightbutton.enabled = textView.hasText;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.5 animations:^{
        self.textView.frame = CGRectMake(15, 64, WIDTH - 30, HEIGHT * 2 / 7);
        self.chooseButton.frame = CGRectMake(WIDTH / 2-50, 64 + HEIGHT * 2 / 7 + 30, 100, 30);
        self.picView.frame = CGRectMake(10, 64 + HEIGHT * 2 / 7, 100, 100);
    }];
    return YES;
}



@end
